package com.pan.util;

import org.junit.jupiter.api.Test;

import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;

/**
 * @author by panstark
 * @description
 * @notice
 * @date 2020/11/28
 **/
public class StringUtil {

    /**
     * JVM加载class文件读取时候使用Unicode编码方式正确读取class文件，那么原来定义的String s="汉字";在内存中的表现形式是Unicode编码。
     * 当调用String.getBytes()的时候，其实已经为乱码买下了祸根。因为此方法使用平台默认的字符集来获取字符串对应的字节数组。
     * @throws UnsupportedEncodingException
     */
    @Test
    public void StringSub() throws UnsupportedEncodingException {

        System.out.println("当前JRE：" + System.getProperty("java.version"));
        System.out.println("当前JVM的默认字符集：" + Charset.defaultCharset());

        String message= "一二三四五六七八九十";
        String sub1 = message.substring(2);
        System.out.println("sub1:"+sub1.length());
        String sub2 = message.substring(2,5);
        System.out.println("sub2:"+sub2.length());

        byte[] sub2Bytes = sub2.getBytes();
        System.out.println("sub2Bytes:"+sub2Bytes.length);
        for (byte sub2Byte : sub2Bytes) {
            System.out.println(sub2Byte);
        }
        String sub3  = new String(sub2Bytes,"GBK");
        System.out.println(sub3+":"+sub3.length());
        System.out.println("sub3Byte:"+sub3.getBytes().length);
        String sub4  = new String(sub2Bytes,"UTF-8");
        System.out.println(sub4+":"+sub4.length());
        System.out.println("sub4Byte:"+sub4.getBytes().length);

    }
}
